package org.mspring.mlog.service.stat.impl;

import java.util.List;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.mspring.mlog.entity.Post;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.service.stat.PostStatService;
import org.mspring.platform.cache.service.CacheService;
import org.mspring.platform.dao.hibernate.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013年9月5日
 */
@Service
@Transactional
public class PostStatServiceImpl extends BaseDao implements PostStatService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private PostService postService;

    // 缓存帖子点击率的缓存对象名称
    public static final String POST_VIEW_CACHENAME = "POST_VIEW";

    @Override
    public void setViews(Long id) {
        // TODO Auto-generated method stub
        if (id == null) {
            return;
        }
        Object value = cacheService.getCacheValue(POST_VIEW_CACHENAME, id.toString());
        Long views = Long.valueOf(0);
        if (value == null) {
            Post post = postService.get(id);
            if (post != null && post.getViews() != null) {
                views = post.getViews();
            }
        } else {
            views = Long.valueOf(value.toString());
        }
        views = views + 1;
        cacheService.updateCacheValue(POST_VIEW_CACHENAME, id.toString(), views);
    }

    @Override
    public Long getViews(Long id) {
        // TODO Auto-generated method stub
        Object value = cacheService.getCacheValue(POST_VIEW_CACHENAME, id.toString());
        Long views = Long.valueOf(0);
        if (value != null) {
            views = Long.valueOf(value.toString());
        } else {
            Post post = postService.get(id);
            if (post != null && post.getViews() != null) {
                views = post.getViews();
            }
        }
        return views;
    }

    @Override
    public void views2DB() {
        // TODO Auto-generated method stub
        Ehcache cache = cacheService.getCache(POST_VIEW_CACHENAME);
        List<String> keys = cache.getKeys();
        if (keys == null || keys.size() <= 0) {
            return;
        }
        for (String id : keys) {
            Element e = cache.get(id);
            Long views = Long.parseLong(e.getValue().toString());
            executeUpdate("update Post post set post.views = ? where post.id = ?", views, Long.valueOf(id));
        }
        cache.removeAll();
    }
}
